package adsi.persistence;

import java.sql.*;
import java.util.logging.*;

public class Database {

    private final static Database instance = new Database();
    private Connection conn;
    private final String dbHost = "localhost";
    private final String dbName = "sclm";
    private final String dbUser = "sclm_user";
    private final String dbPwd = "sclmdb";

    private Database() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + "/" +
                    dbName + "?user=" + dbUser + "&password=" + dbPwd);
        } catch (SQLException ex) {
            Logger.getLogger("logger").log(Level.SEVERE, "Error al conectar con la base de datos.", ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger("logger").log(Level.SEVERE, "Error en el driver de la BD.", ex);
        }
    }

    public static Database getInstance() {
        return instance;
    }

    public ResultSet executeQuery(String sql) throws DataServiceException {
        Statement stmt = null;
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            System.out.println("executeQuery " + sql);
        } catch (SQLException ex) {
            System.out.println("asdasd" + ex.getMessage());
            ex.printStackTrace();
            throw new DataServiceException("Error en la conexión con la base de datos");
        }

        return rs;
    }

    public int executeUpdate(String sql) throws DataServiceException {
        int res;
        Statement stmt = null;

        System.out.println("executeQuery " + sql);
        try {
            stmt = conn.createStatement();
            res = stmt.executeUpdate(sql);
        } catch (SQLException ex) {
            throw new DataServiceException("Error de SQL: " + ex.getMessage());
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException ex) {
                    Logger.getLogger("logger").log(Level.WARNING, "Error al cerrar los recursos.", ex);
                }
            }
        }

        return res;
    }

    public long[] executeUpdate(String sql, boolean rgk) throws DataServiceException {
        long[] res = new long[2];

        if (rgk) {
            Statement stmt = null;
            ResultSet rs = null;

            System.out.println("executeQuery " + sql);
            try {
                stmt = conn.createStatement();
                res[0] = stmt.executeUpdate(sql);
                rs = stmt.getGeneratedKeys();
                if (rs.next()) {
                    res[1] = rs.getLong(1);
                } else {
                    throw new DataServiceException("Error al recuperar el ID del registro recién insertado.");
                }
            } catch (SQLException ex) {
                throw new DataServiceException("Error en la conexión con la base de datos");
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException ex) {
                        Logger.getLogger("logger").log(Level.WARNING, "Error al cerrar los recursos.", ex);
                    }
                }

                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException ex) {
                        Logger.getLogger("logger").log(Level.WARNING, "Error al cerrar los recursos.", ex);
                    }
                }
            }
        } else {
            res[0] = executeUpdate(sql);
            res[1] = -1;
        }

        return res;
    }

    public void closeRS(ResultSet rs) {
        String err = "Error al cerrar los recursos.";
        if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException ex) {
                Logger.getLogger("logger").log(Level.WARNING, err, ex);
            }
        }
    }
}

